<template>
  <div class="register-container" :class="{ 'mobile-layout': isMobileDevice }">
    <div class="register-wrapper">
      <!-- 移动端Logo区域 -->
      <div v-if="isMobileDevice" class="mobile-logo">
        <div class="logo-icon">
          <el-icon size="48"><UserFilled /></el-icon>
        </div>
        <h1>注册账户</h1>
        <p>创建您的流量监控账户</p>
      </div>

      <el-card class="register-card" :class="{ 'mobile-card': isMobileDevice }">
        <template #header v-if="!isMobileDevice">
          <h2>注册账户</h2>
          <p>创建您的流量监控账户</p>
        </template>
        
        <div v-if="isMobileDevice" class="mobile-form-header">
          <h3>账户注册</h3>
        </div>

        <el-form
          ref="registerFormRef"
          :model="registerForm"
          :rules="registerRules"
          :size="isMobileDevice ? 'default' : 'large'"
          :label-position="isMobileDevice ? 'top' : 'right'"
          class="register-form"
        >
        <FormField
          type="input"
          prop="username"
          v-model="registerForm.username"
          placeholder="请输入用户名"
          :rules="registerRules.username"
        />
        
        <!-- <FormField
          type="input"
          input-type="email"
          prop="email"
          v-model="registerForm.email"
          placeholder="请输入邮箱地址（可选）"
          :rules="registerRules.email"
        /> -->
        
        <FormField
          type="input"
          input-type="password"
          prop="password"
          v-model="registerForm.password"
          placeholder="请输入密码"
          :rules="registerRules.password"
        />
        
        <FormField
          type="input"
          input-type="password"
          prop="confirmPassword"
          v-model="registerForm.confirmPassword"
          placeholder="请再次输入密码"
          :rules="registerRules.confirmPassword"
        />
        
        <FormField
          type="input"
          prop="inviteCode"
          v-model="registerForm.inviteCode"
          placeholder="请输入邀请码"
          :rules="registerRules.inviteCode"
        >
          <template #append>
            <el-button 
              @click="validateInviteCode1" 
              :loading="validatingInvite"
              :disabled="!registerForm.inviteCode"
            >
              验证
            </el-button>
          </template>
        </FormField>
        
        <!-- 邀请码验证结果 -->
        <div v-if="inviteCodeInfo" class="invite-code-info">
          <el-alert
            :title="`邀请码：${inviteCodeInfo.code}`"
            :type="inviteCodeInfo.isValid ? 'success' : 'error'"
            :description="getInviteCodeDescription(inviteCodeInfo)"
            show-icon
            :closable="false"
          />
        </div>

          <el-form-item class="register-actions">
            <el-button
              type="primary"
              :class="{ 'mobile-register-btn': isMobileDevice }"
              style="width: 100%"
              :loading="loading"
              @click="handleRegister"
            >
              注册
            </el-button>
          </el-form-item>

          <el-form-item class="login-link">
            <el-button
              type="text"
              style="width: 100%"
              @click="$router.push('/login')"
              :class="{ 'mobile-text-btn': isMobileDevice }"
            >
              已有账户？立即登录
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { UserFilled } from '@element-plus/icons-vue'
import { register, validateInviteCode } from '@/api/auth'
import FormField from '@/components/FormField.vue'

const router = useRouter()

const registerFormRef = ref()
const loading = ref(false)
const validatingInvite = ref(false)
const inviteCodeInfo = ref(null)

// 移动端检测
const isMobileDevice = computed(() => {
  return window.innerWidth <= 768 || document.body.classList.contains('mobile-device')
})

const registerForm = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  inviteCode: ''
})

const validateConfirmPassword = (rule, value, callback) => {
  if (value !== registerForm.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, message: '用户名至少3位', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码至少6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ],
  inviteCode: [
    { required: true, message: '请输入邀请码', trigger: 'blur' },
    { min: 6, message: '邀请码至少6位', trigger: 'blur' }
  ]
}

// 验证邀请码
const validateInviteCode1 = async () => {
  if (!registerForm.inviteCode) {
    ElMessage.warning('请输入邀请码')
    return
  }
  
  try {
    validatingInvite.value = true
    const response = await validateInviteCode(registerForm.inviteCode)
    
    inviteCodeInfo.value = {
      code: response.inviteCode.code,
      type: response.inviteCode.type,
      expiresAt: response.inviteCode.expiresAt,
      maxUses: response.inviteCode.maxUses,
      description: response.inviteCode.description,
      isValid: true
    }
    
    ElMessage.success('邀请码验证成功')
  } catch (error) {
    inviteCodeInfo.value = {
      code: registerForm.inviteCode,
      isValid: false,
      error: error.response?.data?.message || '邀请码无效'
    }
    ElMessage.error('邀请码验证失败')
  } finally {
    validatingInvite.value = false
  }
}

// 获取邀请码描述
const getInviteCodeDescription = (info) => {
  if (!info.isValid) {
    return info.error || '邀请码无效或已过期'
  }
  
  let desc = `类型：${getInviteTypeName(info.type)}`
  
  if (info.expiresAt) {
    const expireDate = new Date(info.expiresAt)
    desc += `\n有效期：${expireDate.toLocaleDateString()}`
  } else {
    desc += '\n有效期：永不过期'
  }
  
  desc += `\n使用次数：${info.maxUses}次`
  
  if (info.description) {
    desc += `\n描述：${info.description}`
  }
  
  return desc
}

// 获取邀请码类型名称
const getInviteTypeName = (type) => {
  const typeMap = {
    'INVITE': '普通邀请',
    'ADMIN': '管理员邀请',
    'SPECIAL': '特殊邀请'
  }
  return typeMap[type] || type
}

const handleRegister = async () => {
  if (!registerFormRef.value) return
  
  try {
    await registerFormRef.value.validate()
    loading.value = true
    
    // 准备注册数据，如果邮箱为空则不发送
    const registerData = {
      username: registerForm.username,
      password: registerForm.password,
      inviteCode: registerForm.inviteCode
    }
    
    // 只有当邮箱不为空时才添加邮箱字段
    if (registerForm.email && registerForm.email.trim()) {
      registerData.email = registerForm.email.trim()
    }
    
    await register(registerData)
    
    ElMessage.success('注册成功，请登录')
    router.push('/login')
  } catch (error) {
    console.error('注册失败:', error)
    ElMessage.error(error.message || '注册失败')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.register-container.mobile-layout {
  align-items: flex-start;
  padding: 0;
  background: #f8f9fa;
}

.register-wrapper {
  width: 100%;
  max-width: 400px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

/* 移动端Logo区域 */
.mobile-logo {
  text-align: center;
  padding: 40px 20px 30px 20px;
  color: white;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  width: 100%;
  border-radius: 0 0 24px 24px;
  margin-bottom: 20px;
}

.logo-icon {
  margin-bottom: 16px;
}

.mobile-logo h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: white;
}

.mobile-logo p {
  margin: 0;
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
}

/* 注册卡片 */
.register-card {
  width: 100%;
  max-width: 400px;
  border-radius: 8px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.register-card.mobile-card {
  margin: 0 16px;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.register-card :deep(.el-card__header) {
  text-align: center;
  background: #f8f9fa;
  border-radius: 8px 8px 0 0;
}

.register-card h2 {
  margin: 0 0 8px 0;
  color: #2c3e50;
}

.register-card p {
  margin: 0;
  color: #6c757d;
  font-size: 14px;
}

/* 移动端表单头部 */
.mobile-form-header {
  text-align: center;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
  margin-bottom: 24px;
}

.mobile-form-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

/* 表单样式 */
.register-form {
  padding: 0 4px;
}

.register-actions {
  margin-top: 24px;
}

.mobile-register-btn {
  height: 48px !important;
  font-size: 16px !important;
  border-radius: 8px !important;
  font-weight: 600;
}

.login-link {
  margin-top: 16px;
  margin-bottom: 0;
}

.mobile-text-btn {
  color: #667eea !important;
  font-size: 14px;
}

/* 邀请码验证信息样式 */
.invite-code-info {
  margin-top: 16px;
}

.invite-code-info .el-alert {
  border-radius: 8px;
}

.invite-code-info .el-alert__description {
  white-space: pre-line;
  line-height: 1.6;
}

/* 移动端优化 */
@media (max-width: 480px) {
  .register-container.mobile-layout {
    padding: 0;
  }
  
  .mobile-logo {
    padding: 30px 20px 24px 20px;
    border-radius: 0 0 20px 20px;
  }
  
  .mobile-logo h1 {
    font-size: 20px;
  }
  
  .register-card.mobile-card {
    margin: 0 12px;
  }
  
  .mobile-form-header h3 {
    font-size: 16px;
  }
}

/* 键盘弹起时的适配 */
@media (max-height: 600px) {
  .mobile-logo {
    padding: 20px 20px 16px 20px;
  }
  
  .mobile-logo h1 {
    font-size: 18px;
  }
  
  .mobile-logo p {
    font-size: 12px;
  }
}

/* 横屏适配 */
@media (max-width: 768px) and (orientation: landscape) {
  .register-container.mobile-layout {
    flex-direction: row;
    align-items: center;
    justify-content: center;
    padding: 20px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  }
  
  .mobile-logo {
    display: none;
  }
  
  .register-card.mobile-card {
    margin: 0;
    max-width: 350px;
  }
}
</style>
